import { onMounted, ref } from 'vue';
import { Access, accessService } from '@/services/authorization/Access';
import { HttpUtil } from '@/utils/HttpUtil';
import { Ref } from '@vue/reactivity';

export interface UseSearchAuthority {
  content: Ref<string>;
  filterAuthorities: Ref<Access[]>;
  // querySearch: (query: string, cb: (data: any[]) => void) => void;
  // handleSelect: (text: string) => void;
  querySearch: (query: string) => void;
}

export const useSearchAuthority = (): UseSearchAuthority => {
  const content = ref('');
  const authorities = ref([] as Access[]);
  const filterAuthorities = ref([] as Access[]);
  const querySearch = (query: string): void => {
    filterAuthorities.value = query
      ? authorities.value.filter(authority => authority.code.toLowerCase().indexOf(query.toLowerCase()) === 0)
      : authorities.value;
  };
  onMounted(async () => {
    const resp = await accessService.selectAll();
    authorities.value = HttpUtil.getList(resp);
    filterAuthorities.value = authorities.value;
  });
  return {
    content,
    filterAuthorities,
    querySearch,
  };
};
